﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CompanyHubServer.Models;
using CompanyHubServer.DAL;
using Ionic.Zip;
using System.Xml.Linq;
using System.Xml;
using System.IO;

namespace CompanyHubServer.Controllers
{
    public class AppController : Controller
    {
        private HubContext db = new HubContext();

        public ActionResult Index()
        {
            var test = db.Packages.ToList();

            var packages = db.Packages.Where(p => !p.IsHistory).OrderBy(p => p.Title);

            return View(packages);
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {

            if (file.ContentLength > 0)
            {
                var curDT = DateTime.Now.ToString("yyyyMMddHHmmss");

                var fileName = curDT + Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Downloads/"), fileName);
                file.SaveAs(path);


                using (ZipFile zipfile = ZipFile.Read(path))
                {
                    var entry = zipfile.Entries.Where(e => e.FileName == "WMAppManifest.xml").FirstOrDefault();

                    if (entry != null)
                    {
                        var memStream = new MemoryStream();
                        entry.Extract(memStream);
                        memStream.Seek(0, 0);

                        var doc = XDocument.Load(memStream);

                        XNamespace name = XNamespace.Get("http://schemas.microsoft.com/windowsphone/2012/deployment");

                        var deployNode = doc.Element(name + "Deployment");
                        var appNode = deployNode.Element("App");

                        var pkg = db.Packages.Create();

                        pkg.PackageId = Guid.Parse(appNode.Attribute("ProductID").Value);
                        pkg.Title = appNode.Attribute("Title").Value;
                        pkg.Author = appNode.Attribute("Author").Value;
                        pkg.Publisher = appNode.Attribute("Publisher").Value;
                        pkg.PublisherId = Guid.Parse(appNode.Attribute("PublisherID").Value);
                        pkg.Description = appNode.Attribute("Description").Value;
                        pkg.Version = appNode.Attribute("Version").Value;
                        pkg.SourceUri = fileName;
                        pkg.UpdatedDT = DateTime.Now;
                        pkg.IsActive = true;
                        pkg.IsHistory = false;

                        if(!String.IsNullOrEmpty(Request["isHub"]))
                            pkg.IsCompanyHub = bool.Parse(Request["isHub"]);
                        else
                            pkg.IsCompanyHub = false;

                        var iconNode = appNode.Element("IconPath").Value;


                        var iconEntry = zipfile.Entries.Where(e => e.FileName == iconNode).FirstOrDefault();
                        var iconMemStream = new MemoryStream();

                        var ext = iconEntry.FileName.Split(new char[] { '.' }).Last();
                        pkg.Thumbnail = curDT + pkg.PackageId.ToString().Replace("-", "") + "." + ext;
                        var iconPath = Path.Combine(Server.MapPath("~/Downloads/"), pkg.Thumbnail);
                        var iconStream = System.IO.File.OpenWrite(iconPath);

                       
                        iconEntry.Extract(iconStream);
                        iconStream.Close();

                        var hubPkgs = db.Packages.Where(p => p.PackageId != pkg.PackageId && !p.IsHistory && p.IsCompanyHub);

                        foreach (var hubPkg in hubPkgs)
                        {
                            hubPkg.IsCompanyHub = false;
                        }

                        var oldPkgs = db.Packages.Where(p => p.PackageId == pkg.PackageId);

                        foreach (var oldPkg in oldPkgs)
                        {
                            oldPkg.IsHistory = true;
                        }

                        db.Packages.Add(pkg);

                        db.SaveChanges();
                    }
                   
                }
            }

            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}